package com.libservice.datarepositories

import com.google.gson.Gson
import com.libbase.cast
import com.libbase.datarepository.DataRepository
import com.libbase.datarepository.DataRepositoryInterface
import com.libbase.utils.JsonUtils
import com.libservice.ServiceManager
import com.libservice.models.DeviceModel

class DeviceModelRepository : DataRepository<DeviceModel>(
    ServiceManager.instance.cacheService.globalCache.getObject(
        builder.id,
        DeviceModel::class.java,
        gson = gson
    ) ?: run {
        val data = DeviceModel()
        ServiceManager.instance.cacheService.globalCache.setObject(builder.id, data, gson = gson)
        data
    }
) {
    companion object {
        val gson: Gson = JsonUtils.jsonBuilder.excludeFieldsWithoutExposeAnnotation().create()

        val builder = object : DataRepositoryInterface.Builder {
            override val id: String = "DeviceModelRepository"

            override fun build(): DataRepositoryInterface {
                return DeviceModelRepository()
            }
        }
    }

    override val id: String
        get() {
            return builder.id
        }

    override fun encode(data: DeviceModel): Any {
        return data.toMap()
    }

    override fun decode(data: Any): DeviceModel? {
        val map: Map<String, Any> = cast(data) ?: return null
        return DeviceModel.create(map)
    }

    override fun save() {
        if (data == null) {
            ServiceManager.instance.cacheService.globalCache.remove(id)
        } else {
            ServiceManager.instance.cacheService.globalCache.setObject(id, data, gson)
        }
    }
}